package org.datavis.renderer;

import java.util.ArrayList;

import org.datavis.chart.Chart;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;

public class LineChartRenderer extends ChartRenderer {

	public LineChartRenderer(Context context) {
		super(context);
    }
	public LineChartRenderer(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	
	public LineChartRenderer(Context context, Chart chart) {
		super(context, chart);
	}
	
	@Override
	public void onDraw(Canvas c) {
	
		super.onDraw(c);
		canvas.drawColor(0, android.graphics.PorterDuff.Mode.CLEAR);
		
		mPaint = new Paint(); 
		mPaint.setColor(0xFF000000);  
		mPaint.setStyle(Paint.Style.FILL);
		
		//draw origin
		mPaint.setStrokeWidth(0.3f);
		DashPathEffect dashPath = new DashPathEffect(new float[]{1,3}, 1);
		mPaint.setPathEffect(dashPath);		
		canvas.drawLine(0, origin, this.getWidth(), origin, mPaint);
		mPaint.setPathEffect(null);
		float lineWidth = chart.getLineWidth();
		mPaint.setStrokeWidth(lineWidth);
		
		//calculate and draw lines
		int lineY = 0;
		int lineX = 0;
		int prevLineY = 0;
		int prevLineX = 0;
		int colorIndex = 0;
		
		intervalSize = (int)(this.getWidth()/(data.getValuesPerEntry()));
		
		for(ArrayList<Double> values: data.getValues())
		{	
			lineY = 0;
			lineX = 0;
			prevLineY = 0;
			prevLineX = 0;
			
			//set color
			mPaint.setColor(colors[(colorIndex % colors.length)]); 
			colorIndex++;
			
			for (int i = 0; i < values.size(); i++)
			{
				//calculate line y from value
				lineY = calculateHeight(data.getValueRange(), values.get(i));
				lineX = (intervalSize/2) + (i*intervalSize);
				
				//draw line after second data item
				if (values.get(i) < 0.)
					lineY = origin + lineY;
				else
					lineY = origin - lineY;
				if (i != 0)
					canvas.drawLine(prevLineX, prevLineY, lineX, lineY, mPaint);
				
				//draw circle at data point
				canvas.drawCircle(lineX, lineY, lineWidth, mPaint);
				
				prevLineY = lineY;
				prevLineX = lineX;
			}
		}
		
		if(chart.getZoomModus() == Chart.ZOOMIN)
			setDrawSelectionRect();
		
		//draw the bitmap to the real canvas c
		c.drawBitmap(bitmap, 
			new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()), 
			new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()), null);
		
	}

}